package com.hl.socket;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import com.hl.util.CodeAttribute;


/**
 * 创建服务器类
 * @author Administrator
 *
 */
public class CreateServer {
	/**
	 * 创建服务器
	 */
	public void create() {
		Map<String,CodeAttribute> map = new HashMap<>(); //定义一个全局map,用来管理socket连接和关闭
		ExecutorService executorService = Executors.newFixedThreadPool(30); //线程池
		//将exes转换为ThreadPoolExecutor,ThreadPoolExecutor有方法 getActiveCount()可以得到当前活动线程数
		int threadCount = 0;
		final int PORT = 9999;
		try {
			ServerSocket serverSocket = new ServerSocket(PORT);
			System.out.println("****黄龙原创****  服务器启动,监听端口为 " + PORT + " 等待wifi连接");
			executorService.submit(new Heartbeat(map));  //发送心跳线程
			while(true) {
				Socket socket = serverSocket.accept();  //等待客户端连接 阻塞
				System.out.println("连接成功,客户端信息：" + socket);
				executorService.submit(new SocketInput(socket,map)); //添加到线程池
				threadCount = ((ThreadPoolExecutor) executorService).getActiveCount();
				System.out.println("当前线程池数量: " + threadCount);
				if(threadCount == 30) {
					System.out.println("清空线程池");
					executorService.shutdown();
				}
			}
		} catch (Exception e) {
			System.out.println("服务器创建失败  ---" + e);
			executorService.shutdown();
		}
	}
}
